package org.openslash.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.openslash.resource.StandardResourcePacket;

public class StandardDBAccessor extends DBAccessor{
	private Connection conn;
	private StandardDBAccessor(){}
	
	public static void setUp(String DBFileName, String SQLtext)
	{
		if( dba == null )
		{
			StandardDBAccessor sdba = new StandardDBAccessor();
			try {
				Class.forName("org.sqlite.JDBC");
				sdba.conn = DriverManager.getConnection("jdbc:sqlite:"+DBFileName);
			} catch (SQLException e) {
				e.printStackTrace();
				return;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				return;
			}
			sdba.rp = new StandardResourcePacket(SQLtext);
			dba = sdba;
		}	
	}
	
	public ResultList executeQuery(String sqltext, int[] params)
	{
		StandardResultList srl = null;
		try {
			PreparedStatement prestmt = conn.prepareStatement(sqltext);
			int index = 1;
			if( params != null )
			{
				for(int param : params)
				{
					prestmt.setInt(index++, param);
				}
			}
			srl = new StandardResultList(prestmt.executeQuery());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return srl;
	}

	@Override
	protected void finish() {
		StandardDBAccessor sdba = (StandardDBAccessor) dba;
		try {
			sdba.conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		sdba.conn = null;
		
	}

}
